package com.xing.config.shiro.listener;

import lombok.Data;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationListener;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.SessionException;
import org.apache.shiro.session.mgt.DefaultSessionKey;
import org.apache.shiro.session.mgt.SessionManager;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.RedisScript;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.Collections;

/**
 * Created by Bradish7Y on 2017/9/15.
 * 验证器监听器
 * 参考：https://my.oschina.net/qixiaobo025/blog/906698
 */
@Data
public class KickOutAuthenticationListener implements AuthenticationListener {

    @Resource
    private RedisTemplate<String, Serializable> redisTemplate;

    @Resource(name = "updateKickoutRedisScript")
    private RedisScript<Boolean> redisScript;

    private int maxSession;//最大在线session数
    private String kickoutUrl;//成功踢出后重定向url
    private boolean kickoutAfter = false;//踢出最新登录、后登录，默认踢出之前登录
    private int sessionExpire = 1800;
    private SessionManager sessionManager;

    private boolean kickout;
    public static final String SESSION_KEY_KICKOUT = "kickout";


    @Override
    public void onSuccess(AuthenticationToken token, AuthenticationInfo info) {
        if (!kickout) {
            return;
        }

        Subject subject = SecurityUtils.getSubject();
        HttpServletRequest request = WebUtils.getHttpRequest(subject);
        Session session;
        final String username = token.getPrincipal().toString();
        try {
            session = subject.getSession();
        } catch (SessionException ex) {
            return;
        }
        if (session == null) {
            return;
        }

        String sessionId = (String) session.getId();

        try {
            if (session.getAttribute("kickout") == null) {
                redisTemplate.execute(redisScript, Collections.singletonList(username), sessionId, sessionExpire);
            }

            Long size = redisTemplate.opsForList().size(username);

            //超出最大会话数，开始踢人
            while (size-- > maxSession) {
                Serializable kickoutSessionId = null;
                if (kickoutAfter) { //如果踢出后者
                    kickoutSessionId = redisTemplate.opsForList().rightPop(username);
                } else { //否则踢出前者
                    kickoutSessionId = redisTemplate.opsForList().leftPop(username);
                }
                try {
                    Session kickoutSession = sessionManager.getSession(new DefaultSessionKey(kickoutSessionId));
                    if (kickoutSession != null) {
                        //设置会话的kickout属性表示踢出了
                        kickoutSession.setAttribute(SESSION_KEY_KICKOUT, true);
                    }
                } catch (Exception e) {
                }
            }
        } catch (Exception e) {

        }

    }

    @Override
    public void onFailure(AuthenticationToken token, AuthenticationException ae) {

    }

    @Override
    public void onLogout(PrincipalCollection principals) {

    }
}
